import {createRouter, createWebHistory} from 'vue-router'
import LoginView from '../views/login.vue'
import {ElMessage} from 'element-plus'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'login',
            component: LoginView,
        },
        {
            path: '/index',
            name: 'index',
            component: () => import('@/views/index.vue'),
            children: [
                {path: '/system/user', name: 'user', component: () => import('../views/system/user.vue')},
                {path: '/system/menu', name: 'menu', component: () => import('../views/system/menu.vue')},
                {path: '/system/role', name: 'role', component: () => import('../views/system/role.vue')},
                {path: '/tool/chart', name: 'role', component: () => import('../views/tool/chart.vue')},
            ]
        },
        {
            path: '/404',
            name: '404',
            component: () => import('@/views/404.vue'),
        },
        {path: '/:pathMatch(.*)*', redirect: '/404'}
    ],
})

// 路由守卫
router.beforeEach(async (to, from) => {
    // 检查用户是否已登录
    if (!sessionStorage.getItem("token") && to.name !== 'login') {
        ElMessage.error('请先登录')
        return {name: 'login'} // 将用户重定向到登录页面
    }
})

export default router
